import re
import time
from flask import request
from flask_restful import abort
from flask_login import current_user, login_user
from funcy import project
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import IntegrityError
from funcy import partial

from redash import models, limiter
from redash.permissions import (
    require_permission,
    require_admin_or_owner,
    is_admin_or_owner,
    require_permission_or_owner,
    require_admin_default,
)
from redash.handlers.base import (
    BaseResource,
    require_fields,
    get_object_or_404,
    paginate,
    order_results as _order_results,
)

from redash.authentication.account import (
    invite_link_for_user,
    send_invite_email,
    send_password_reset_email,
    send_verify_email,
)
from redash.settings import parse_boolean
from redash import settings

class GlobalSettingNewResource(BaseResource):
    @require_admin_default
    def post(self):
        req = request.get_json(force=True)
        require_fields(req, ("code","type"))
        globalsetting = models.GlobalSetting(
        userid = req["userid"],
        org=self.current_org,
        code = req["code"],
        type =req["type"],
        value =req["value"],
        message =req["message"],
        )

        try:
            models.db.session.add(globalsetting)
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="KEY已存在.")
            abort(500)

        # timeserial.record_event(
        #     {"action": "create", "object_id": timeserial.id, "object_type": "timeserial"}
        # )

class GlobalSettingResource(BaseResource):
    def get(self, globalsetting_id):
        result = models.GlobalSetting.get_by_id(globalsetting_id)
        return result.to_dict()

    @require_admin_default
    def post(self, globalsetting_id):
        req = request.get_json(force=True)
        require_fields(req, ("code","type"))

        globalsetting = models.GlobalSetting.get_by_id(globalsetting_id)
        params = dict(userid=req["userid"], value =req["value"])

        try:
            self.update_model(globalsetting, params)
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="编号已存在.")
            abort(500)

    @require_admin_default
    def delete(self, globalsetting_id):
        globalsetting =  models.GlobalSetting.get_by_id(globalsetting_id)
        models.db.session.delete(globalsetting)
        models.db.session.commit()
        # if result > 0 :
        #     abort(400, message="模板已使用，不能删除！")
        #     return



class GlobalSettingListResource(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        page = req["page"]
        page_size = req["pagesize"]
        code = req["code"]
        type = req["type"]
        orderfield = req["field"] if "field" in req else ""
        if orderfield=="code":
            orderfield ="t1.code"
        elif orderfield=="type":
            orderfield ="t1.type"
        else:
            orderfield ="t1.type"
        order = req["order"] if "order" in req else 0

        strwhere ="t1.org_id=" +str(self.current_org.id)
        if code !="" :
            strwhere = strwhere + " and t1.code like '%"+code+"%'"
        if type !='' :
            strwhere = strwhere + " and t1.type like '%"+type+"%'"

        strgetfield =""" t1.*"""

        tblname = """public.globalsetting t1 """
        #orderfield ="t1.type,t1.code"
        result = models.ContractApply.get_pagequery(tblname,strgetfield,orderfield,page_size,page,order,strwhere)
        return result[0]
